package com.lagou.rocket.service.impl;

import com.alibaba.fastjson.JSON;
import com.lagou.rocket.dao.OrderDao;
import com.lagou.rocket.dao.ProductDao;
import com.lagou.rocket.dto.OrderDTO;
import com.lagou.rocket.pojo.Order;
import com.lagou.rocket.pojo.Product;
import com.lagou.rocket.service.OrderService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    private final String PRODUCT_NUM = "productNum:";

    /**
     * 下订单
     *
     * @param orderDTO
     * @return
     */
    @Override
    public String createOrder(OrderDTO orderDTO) {
        // 校验redis库存
        String key = PRODUCT_NUM + orderDTO.getPid();
        Integer num = (Integer) redisTemplate.opsForValue().get(key);
        if (num >= orderDTO.getNum()) {
            // 发mq
            orderDTO.setOid(System.currentTimeMillis());
            rocketMQTemplate.convertAndSend("topic_snapped", JSON.toJSONString(orderDTO));
            // 返回订单号
            return orderDTO.getOid().toString();
        } else {
            return "无货";
        }
    }

    /**
     * 保存订单
     *
     * @return
     */
    @Transactional
    @Override
    public Boolean saveOrder(OrderDTO orderDTO) {
        Optional<Product> optionalProduct = productDao.findById(orderDTO.getPid());
        Product product = optionalProduct.get();

        // 判断数量
        if (product.getNum() < orderDTO.getNum()) {
            return false;
        }

        // 减库存
        int num = product.getNum() - orderDTO.getNum();
        productDao.updateProductNum(orderDTO.getPid(), num);
        String key = PRODUCT_NUM + orderDTO.getPid();
        redisTemplate.opsForValue().set(key, num);

        // 下单
        Order order = new Order();
        order.setOid(orderDTO.getOid());
        order.setNum(orderDTO.getNum());
        order.setPid(orderDTO.getPid());
        order.setStatus(0);
        order.setUid(orderDTO.getUid());
        orderDao.save(order);

        // 发mq延迟消息  1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        rocketMQTemplate.syncSend("topic_order_over", MessageBuilder.withPayload(order.getId()).build(), 100, 6);

        return true;
    }

    @Override
    public String pay(Long orderId) {
        orderDao.payOrder(orderId, 1);
        return "支付成功";
    }

    /**
     * 支付
     *
     * @return
     */
    @Override
    public Order getOrderById(Long orderId) {
        Optional<Order> optionalOrder = orderDao.findById(orderId);
        Order order = optionalOrder.get();
        return order;
    }

    @Transactional
    @Override
    public Boolean recovery(Long orderId) {
        Optional<Order> optionalOrder = orderDao.findById(orderId);
        Order order = optionalOrder.get();

        if (order.getStatus() != 0) {
            return true;
        }

        Integer num = order.getNum();

        // 添加库存
        Optional<Product> optionalProduct = productDao.findById(order.getPid());
        Product product = optionalProduct.get();
        productDao.updateProductNum(order.getPid(), num + product.getNum());
        // 缓存添加库存
        String key = PRODUCT_NUM + order.getPid();
        redisTemplate.opsForValue().set(key, num + product.getNum());

        // 修改订单状态为超时
        orderDao.payOrder(orderId, 2);

        return true;
    }
}
